﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using MarkHeath.StarRating;
using OnlineVideos.View_Models;
using Common.Library;
using System.Collections.ObjectModel;
using HtmlAgilityPack;
using Common.Utilities;
using System.Text.RegularExpressions;
using InsertIntoDataBase;
using OnlineVideos.Data;
using System.Threading;
using System.Text;
using System.IO;
using System.Xml.Linq;
using OnlineVideos.UI;
using System.IO.IsolatedStorage;
using OnlineVideos.Entities;
using Windows.Common.Data;
using System.Threading.Tasks;

namespace OnlineMovies.Views
{
    public partial class UserUpload : PhoneApplicationPage
    {
        AddShow addshow = new AddShow();
        public static string imagetype = string.Empty;
        public bool TaskNavigation = false;
        public AutoResetEvent auto = new AutoResetEvent(false);
        public static bool navigated = false;
        ShowDetail showdetail;
        double ratingvalue = 0.0;
        IDictionary<string, int> Dic = new Dictionary<string, int>();
        public UserUpload()
        {
            InitializeComponent();
            showdetail = new ShowDetail();
            Loaded += UserUpload_Loaded;
          
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            Constants.Description.Clear();
            Constants.OnlineImageUrls.Clear();
            Constants.UserImage1 = null;
            Constants.DownloadTimer.Start();
            //tblkshowname.LostFocus -= tblkshowname_LostFocus_1;
        }
        void UserUpload_Loaded(object sender, RoutedEventArgs e)
        {
            LoadAds();
            try
            {
                FlurryWP8SDK.Api.LogEvent("UserUpload Page", true);
            tblkVideosTitle.Text = "CREATE" + " " + AppResources.Type.ToUpper();
            if (ResourceHelper.AppName == Apps.Indian_Cinema.ToString() || ResourceHelper.AppName == Apps.Indian_Cinema_Pro.ToString())
            {
                genr.Text = "Genre";
                if (Dic.Keys.Count == 0)
                {
                    Dictionary<string, int> cat = addshow.GetCat();
                    foreach (var ss in cat)
                    {
                        Dic.Add(ss.Key, ss.Value);
                    }
                    lpiccategory.ItemsSource = Dic.Keys;
                    lpiccategory.SelectedIndex = 0;
                }
              
            }
            else if (ResourceHelper.AppName == Apps.Recipe_Shows.ToString() || ResourceHelper.AppName == Apps.Online_Education.ToString())
            {
                if (Dic.Keys.Count == 0)
                {
                    Dic.Add("--Choose Category--", 0);
                    List<CatageoryTable> cat = addshow.GetCatageories();
                    foreach (CatageoryTable list in cat)
                    {
                        if (!Dic.ContainsKey(list.CategoryName))
                            Dic.Add(list.CategoryName, list.CategoryID);
                    }
                    lpiccategory.ItemsSource = Dic.Keys;
                    lpiccategory.SelectedIndex = 0;
                }
            }
                else if (ResourceHelper.AppName == Apps.Kids_TV_Shows.ToString() || ResourceHelper.AppName == Apps.Kids_TV_Pro.ToString() || ResourceHelper.AppName == Apps.Kids_TV.ToString())
            {
                genr.Text = "Age";
                if (Dic.Keys.Count == 0)
                {
                    Dic.Add("--Choose Category--", 0);
                    //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                    List<ShowList> showlist = addshow.GetShowList();
                    foreach (ShowList list in showlist)
                    {
                        if (list.ReleaseDate != null)
                        {
                            if (!Dic.ContainsKey(list.ReleaseDate))
                                Dic.Add(list.ReleaseDate, 0);
                        }
                    }
                    lpiccategory.ItemsSource = Dic.Keys;
                    lpiccategory.SelectedIndex = 0;
                }
            }
            else
            {

                genr.Visibility = Visibility.Collapsed;
                lpiccategory.Visibility = Visibility.Collapsed;
            }
            type.Text = AppResources.Type + " Name";
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in UserUpload_Loaded event In UserUpload.cs file.", ex);
            }
            
        }

        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, adstackpl, 2);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
      
        }



        private void rating_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            StarRatingControl starratingcontrol = new StarRatingControl();
            starratingcontrol.Rating = rating.Rating;
            ratingvalue = (Convert.ToDouble(starratingcontrol.Rating) / 2);

        }

       
           
        //void wb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        //{
        //    if (e.Result != null)
        //    {

        //        string PageHtml = e.Result.ToString();
        //        Constants.OnlineImageUrls.Clear();
        //      //  getimages(PageHtml);
        //        Regex reg = new Regex("http://[^\\s]+\\.jpg");
        //        Match mat = reg.Match(PageHtml);
        //        while (mat.Success)
        //        {
        //            int startindex = 0;
        //            startindex = mat.Value.ToString().LastIndexOf("http://");

        //            Constants.OnlineImageUrls.Add(mat.Value.Substring(startindex));
        //            mat = mat.NextMatch();
        //        }
        //        Deployment.Current.Dispatcher.BeginInvoke(() =>
        //        {
        //            PageHelper.NavigateToOnlineImagesPage(AppResources.OnlineImagesPageName);
        //        });
        //    }
          
        //}


        //public void getimages(string pagehtml)
        //{
        //    int startlength = "http://".Length;
        //    int endlength = ".jpg".Length;
        //    int currentindex = 0;
        //    int endindex = 0;
        //    int startindex = 0;
        //    while (pagehtml.Length > currentindex)
        //    {
        //        endindex = pagehtml.Substring(currentindex).IndexOf(".jpg");
        //        startindex = pagehtml.Substring(currentindex, endindex).LastIndexOf("http://");
        //        currentindex = endindex + endlength - 1;
        //        Constants.OnlineImageUrls.Add(pagehtml.Substring(startindex, currentindex));
        //    }



        //}
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.EndTimedEvent("UserUpload Page");
            if (e.NavigationMode != NavigationMode.Back)
            {
                Constants.Description.Clear();
                Constants.Description.Append(tblkdes.Text);
            }
        }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedFrom event In UserUpload.cs file.", ex);
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.LogPageView();
            if (TaskNavigation == false)
            {
                    if (Constants.Description.Length > 0)
                {
                    txtlimit.Visibility = Visibility.Collapsed;
                    tblkdes.Text = Constants.Description.ToString();
                    txtlength.Text = Convert.ToString(tblkdes.Text.Length) + "/" + Convert.ToString(4000);
                    
                }
                if (Constants.UserImage1 != null)
                {
                    
                        if (navigated == false && Constants.navigation == false)
                        {
                            navigated = true;
                            NavigationService.Navigate(new Uri("/Views/PhotoChooser.Xaml?ImageName=" + tblkshowname.Text, UriKind.Relative));
                        }
                        else
                        {
                            navigated = false;
                            Constants.UIThread = true;
                            if (imagetype == "LocalImage")
                            {
                                userlocalimg.Source = ResourceHelper.getShowTileImage(tblkshowname.Text + ".jpg");
                                useronlineimg.Source = new BitmapImage(new Uri("/Images/fromonline.png", UriKind.RelativeOrAbsolute));
                            }
                            if (imagetype == "OnlineImage")
                            {
                                useronlineimg.Source = ResourceHelper.getShowTileImage(tblkshowname.Text + ".jpg");
                                userlocalimg.Source = new BitmapImage(new Uri("/Images/fromlocal.png", UriKind.RelativeOrAbsolute));
                            }
                         
                            Constants.UIThread = false;
                            Constants.UserImage1 = null;
                        }
                    
                }
                else
                    Constants.navigation = false;
            }
            else
            {
                TaskNavigation = false;
            }
        }
            catch (Exception ex)
            {

                 Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo event In UserUpload.cs file.", ex);
            }
        }

        private void btnsave_Click_1(object sender, EventArgs e)
        {
            try
            {
            if (!string.IsNullOrEmpty(tblkshowname.Text))
            {
                valid.Visibility = Visibility.Collapsed;
                if (tblkdes.Text.Length > 4000)
                {

                    txtlimit.Visibility = Visibility.Visible;
                }
                else
                {
                    txtlimit.Visibility = Visibility.Collapsed;
                    IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
                    //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                    InsertData<ShowList> insert = new InsertData<ShowList>();
              
                    insert.ParameterList = new ShowList();

                    insert.ParameterList.ShowID = (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.Status == "Custom").OrderByDescending(i => i.ShowID).FirstOrDefaultAsync()).Result != null) ? Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.Status == "Custom").OrderByDescending(i => i.ShowID).FirstOrDefaultAsync()).Result.ShowID + 1 : 1;
                    insert.ParameterList.Title = tblkshowname.Text;
                    insert.ParameterList.Description = tblkdes.Text;
                    insert.ParameterList.Rating = ratingvalue;
                    insert.ParameterList.Status = "Custom";
                    insert.ParameterList.CreatedDate = System.DateTime.Now;

                    if (ResourceHelper.AppName == Apps.Kids_TV_Shows.ToString() || ResourceHelper.AppName == Apps.Kids_TV_Pro.ToString() || ResourceHelper.AppName == Apps.Kids_TV.ToString())
                    {
                        insert.ParameterList.ReleaseDate = lpiccategory.SelectedItem.ToString();
                        insert.ParameterList.SubTitle = "English";
                    }
                    else if (ResourceHelper.AppName == Apps.Story_Time.ToString() || ResourceHelper.AppName == Apps.Animation_Planet.ToString() || ResourceHelper.AppName == Apps.Vedic_Library.ToString())
                        insert.ParameterList.SubTitle = "English";
                    else
                    {
                            insert.ParameterList.ReleaseDate = System.DateTime.Now.ToString();
                        insert.ParameterList.SubTitle = "None";
                    }
                    //if (lpic.SelectedIndex == 2)
                    //{
                    if (!iso.FileExists("/Images/" + tblkshowname.Text + ".jpg"))
                        insert.ParameterList.TileImage = "Default.jpg";
                    else
                        insert.ParameterList.TileImage = tblkshowname.Text + ".jpg";
                    //}
                    //else
                    //{
                    //    insert.ParameterList.TileImage = tblkshowname.Text + ".jpg";
                    //}
                      insert.Insert();
                      if (ResourceHelper.AppName == Apps.Indian_Cinema.ToString() || ResourceHelper.AppName == Apps.Indian_Cinema_Pro.ToString())
                      {
                          InsertData<CategoriesByShowID> insert1 = new InsertData<CategoriesByShowID>();
                          insert1.ParameterList = new CategoriesByShowID();
                          insert1.ParameterList.ShowID = insert.ParameterList.ShowID;
                        
                          insert1.ParameterList.CatageoryID = Dic.Where(i => i.Key == lpiccategory.SelectedItem.ToString()).FirstOrDefault().Value;
                          insert1.Insert();
                      }
                      else if (ResourceHelper.AppName == Apps.Bollywood_Movies.ToString() || ResourceHelper.AppName == Apps.Bollywood_Music.ToString())
                      {
                          InsertData<CategoriesByShowID> insert1 = new InsertData<CategoriesByShowID>();
                          insert1.ParameterList = new CategoriesByShowID();
                          insert1.ParameterList.ShowID = insert.ParameterList.ShowID;

                            insert1.ParameterList.CatageoryID = 7;
                          insert1.Insert();
                      }
                      else if (ResourceHelper.AppName == Apps.Recipe_Shows.ToString() || ResourceHelper.AppName == Apps.Online_Education.ToString())
                      {
                          InsertData<CategoriesByShowID> insert1 = new InsertData<CategoriesByShowID>();
                          insert1.ParameterList = new CategoriesByShowID();
                          insert1.ParameterList.ShowID = insert.ParameterList.ShowID;

                          insert1.ParameterList.CatageoryID = Dic.Where(i => i.Key == lpiccategory.SelectedItem.ToString()).FirstOrDefault().Value;
                          insert1.Insert();
                      }
                      if (ResourceHelper.AppName != Apps.Story_Time.ToString() && ResourceHelper.AppName != Apps.Vedic_Library.ToString() && ResourceHelper.AppName != Apps.Online_Education.ToString() && ResourceHelper.AppName != Apps.Fitness_Programs.ToString() && ResourceHelper.AppName != Apps.DrivingTest.ToString() && ResourceHelper.AppName != Apps.World_Dance.ToString())
                      {
                          if (insert.ParameterList.ShowID == 1)
                          {
                              AppSettings.MinPersonID = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID > 1).OrderBy(i => i.PersonID).FirstOrDefaultAsync()).Result.PersonID;
                          }
                      }
                    Constants.Description.Clear();
                    Constants.OnlineImageUrls.Clear();
                    Constants.DownloadTimer.Start();
                    NavigationService.GoBack();
                }
            }
            else
            {
                valid.Visibility = Visibility.Visible;
            }
        }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in btnsave_Click_1 event In UserUpload.cs file.", ex);
            }
        }

        private void tblkshowname_LostFocus_1(object sender, RoutedEventArgs e)
        {
            //if (tblkshowname.Text.Length > 0)
            //{
            //    valid.Visibility = Visibility.Collapsed;
            //}
            //else
            //{
            //    valid.Visibility = Visibility.Visible;
            //    tblkshowname.Focus();
            //}
        }

        private void tblkshowname_Loaded_1(object sender, RoutedEventArgs e)
        {
            //if (tblkshowname.Text.Length == 0)
            //{
            //    tblkshowname.Focus();
            //}
        }

        
        private void imgTitle_MouseEnter(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            NavigationService.Navigate(NavigationHelper.MainPanoramaPage);
        }

        private void edit_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Constants.navigation = true;
            Constants.Description.Clear();
            Constants.Description.Append(tblkdes.Text);
            NavigationService.Navigate(new Uri("/Views/Description.Xaml", UriKind.Relative));
        }

        private void userlocalimg_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
            Constants.navigation = true;
            imagetype = "LocalImage";
            PhotoChooserTask task = new PhotoChooserTask();
            task.Completed += task_Completed;
            task.Show();
            TaskNavigation = true;
        }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in userlocalimg_MouseLeftButtonDown_1 event In UserUpload.cs file.", ex);
            }
        }
        void task_Completed(object sender, PhotoResult e)
        {
            try
            {
            if (e.TaskResult == TaskResult.OK)
            {
                Constants.UserImage1 = new BitmapImage();
                Constants.UserImage1.SetSource(e.ChosenPhoto);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.Navigate(new Uri("/Views/PhotoChooser.Xaml?ImageName=" + tblkshowname.Text, UriKind.Relative));

                });

                // userimg.Source = bitmapimage;
            }
            }
            catch (Exception ex)
            {

                 Exceptions.SaveOrSendExceptions("Exception in task_Completed event In UserUpload.cs file.", ex);
            }


        }

        public void useronlineimg_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
            Constants.navigation = false;
            imagetype = "OnlineImage";
            WebClient wb = new WebClient();
                if (ResourceHelper.AppName == Apps.Online_Education.ToString())
                wb.DownloadStringAsync(new Uri(" http://www.bing.com/images/search?q=" + tblkshowname.Text + " Subject", UriKind.Absolute));
                else if (ResourceHelper.AppName == Apps.DrivingTest.ToString())
                wb.DownloadStringAsync(new Uri(" http://www.bing.com/images/search?q=" + tblkshowname.Text, UriKind.Absolute));
            else
           wb.DownloadStringAsync(new Uri(" http://www.bing.com/images/search?q=" + tblkshowname.Text + " Movie", UriKind.Absolute));
            wb.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wb_DownloadStringCompleted);
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in useronlineimg_MouseLeftButtonDown_1 event In UserUpload.cs file.", ex);
            }
            //var bingKey = Constants.bingsearch(ResourceHelper.AppName);
            //var authentication = string.Format("{0}:{1}", string.Empty, bingKey);
            //var encodedKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(authentication));
            ////HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Image%27&Query=%27Yevadu%27&Adult=%27Off%27&ImageFilters=%27Size%3AMedium%27");
            //HttpWebRequest request = (ResourceHelper.AppName==Apps.Online_Education.ToString()) ? (HttpWebRequest)WebRequest.Create("https://api.datamarket.azure.com/Bing/Search/v1/Image?Query='" + tblkshowname.Text + " Subject" + "'&ImageFilters=%27Style%3aPhoto%2bSize%3aMedium%2bAspect%3aTall%27&$top=50&$format=Atom") : (HttpWebRequest)WebRequest.Create("https://api.datamarket.azure.com/Bing/Search/v1/Image?Query='" + tblkshowname.Text + " Movie" + "'&ImageFilters=%27Style%3aPhoto%2bSize%3aMedium%2bAspect%3aTall%27&$top=50&$format=Atom");
            //request.Method = "GET";
            //request.Headers["Authorization"] = "Basic " + encodedKey;
            //request.BeginGetResponse(new AsyncCallback(RequestBlogCompleted), request);

        }
        void wb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {

                    string PageHtml = e.Result.ToString();
                    Constants.OnlineImageUrls.Clear();

                    Constants.OnlineImageUrls = GetImages(PageHtml);
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        PageHelper.NavigateToOnlineImagesPage(AppResources.OnlineImagesPageName);
                    });
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in wb_DownloadStringCompleted event In UserUpload.cs file.", ex);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    PageHelper.NavigateToOnlineImagesPage(AppResources.OnlineImagesPageName);
                });
            }

        }

        public ObservableCollection<string> GetImages(string input)
        {
            ObservableCollection<string> list = new ObservableCollection<string>();
            try
            {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(input);

            foreach (HtmlNode node in doc.DocumentNode.SelectNodes(" //img"))
            {
                if (node.OuterHtml.Contains("src") || node.OuterHtml.Contains("data-src") || node.OuterHtml.Contains("dfr-src") || node.OuterHtml.Contains("deferredsrc") || node.OuterHtml.Contains("src2"))
                {
                    if (((node.Attributes["src"] == null) ? (node.Attributes["data-src"] == null) ? (node.Attributes["src2"] == null) ? (node.Attributes["dfr-src"] == null) ? node.Attributes["deferredsrc"] : node.Attributes["dfr-src"] : node.Attributes["src2"] : node.Attributes["data-src"] : node.Attributes["src"]).Value.StartsWith("http"))
                    {


                        list.Add(((node.Attributes["src"] == null) ? (node.Attributes["data-src"] == null) ? (node.Attributes["src2"] == null) ? (node.Attributes["dfr-src"] == null) ? node.Attributes["deferredsrc"] : node.Attributes["dfr-src"] : node.Attributes["src2"] : node.Attributes["data-src"] : node.Attributes["src"]).Value);
                    }
                   
                }
                }
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in GetImages event In UserUpload.cs file.", ex);
            }
            return list;
        }


     
      
        private void RequestBlogCompleted(IAsyncResult result)
        {
            try
            {
                var request = (HttpWebRequest)result.AsyncState;
                var response = (HttpWebResponse)request.EndGetResponse(result);
                StreamReader responseReader = new StreamReader(response.GetResponseStream());
                string responseStr = responseReader.ReadToEnd();
                Stream strm = new MemoryStream(Encoding.UTF8.GetBytes(responseStr));
                XElement MyXMLConfig = XElement.Load(strm);
                XNamespace atomNS = "http://www.w3.org/2005/Atom";
                XNamespace Img = "http://schemas.microsoft.com/ado/2007/08/dataservices";
                XNamespace met = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

                Constants.OnlineImageUrls = new ObservableCollection<string>(MyXMLConfig.Descendants(atomNS + "entry").Descendants(met + "properties").Elements().Where(i => i.Name == Img + "MediaUrl").Select(i => i.Value).ToList());

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    PageHelper.NavigateToOnlineImagesPage(AppResources.OnlineImagesPageName);
                });
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in RequestBlogCompleted  In UserUpload.cs file.", ex);
            }
        }

        private void onlinedescimg_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Constants.navigation = true;
            NavigationService.Navigate(new Uri("/Views/UserBrowserPage.xaml?querytext=" + tblkshowname.Text + "&searchquery=" + string.Empty, UriKind.RelativeOrAbsolute));
        }

        private void tblkdes_TextChanged_1(object sender, TextChangedEventArgs e)
        {
            txtlimit.Visibility = Visibility.Collapsed;
            txtlength.Text = Convert.ToString(tblkdes.Text.Length) + "/" + Convert.ToString(4000);
        }

        private void TextBlock_Loaded_1(object sender, RoutedEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            if (tb.Text.Contains("Choose Category"))
            {
                tb.Visibility = Visibility.Collapsed;
                tb.Loaded -= TextBlock_Loaded_1;
            }
        }

        
    }
}